package com.srmt.document.feishu.internal.core;

import com.lark.oapi.service.docx.v1.model.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Block操作工具类
 * 
 * 提供Block相关的静态工具方法，用于文本提取、类型判断等通用操作。
 * 消除代码重复，提供统一的Block操作方法。
 * 
 * @author srmt
 * @since 2.0.0
 */
public class BlockUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(BlockUtils.class);
    
    // Block类型常量
    public static final int BLOCK_TYPE_PAGE = 1;
    public static final int BLOCK_TYPE_TEXT = 2;
    public static final int BLOCK_TYPE_HEADING1 = 3;
    public static final int BLOCK_TYPE_HEADING2 = 4;
    public static final int BLOCK_TYPE_HEADING3 = 5;
    public static final int BLOCK_TYPE_HEADING4 = 6;
    public static final int BLOCK_TYPE_HEADING5 = 7;
    public static final int BLOCK_TYPE_HEADING6 = 8;
    public static final int BLOCK_TYPE_BULLET = 9;
    public static final int BLOCK_TYPE_ORDERED = 10;
    public static final int BLOCK_TYPE_CODE = 11;
    public static final int BLOCK_TYPE_QUOTE = 13;
    public static final int BLOCK_TYPE_BITABLE = 18;  // 多维表格
    public static final int BLOCK_TYPE_SHEET = 30;   // 电子表格
    public static final int BLOCK_TYPE_TABLE = 31;   // 普通表格
    public static final int BLOCK_TYPE_TABLE_CELL = 32;
    
    private BlockUtils() {
        // 工具类，禁止实例化
    }
    
    /**
     * 从Block中提取纯文本内容
     * 
     * @param block Block对象
     * @return 提取的文本内容，如果没有文本返回空字符串
     */
    public static String extractTextFromBlock(Block block) {
        if (block == null) {
            return "";
        }
        
        Text text = getTextFromBlock(block);
        if (text == null) {
            return "";
        }
        
        return extractTextFromTextObject(text);
    }
    
    /**
     * 从Text对象中提取纯文本
     * 
     * @param text Text对象
     * @return 提取的文本内容
     */
    public static String extractTextFromTextObject(Text text) {
        if (text == null || text.getElements() == null) {
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        
        for (TextElement element : text.getElements()) {
            String elementText = extractTextFromTextElement(element);
            if (!elementText.isEmpty()) {
                sb.append(elementText);
            }
        }
        
        return sb.toString();
    }
    
    /**
     * 从TextElement中提取文本
     * 
     * @param element TextElement对象
     * @return 提取的文本内容
     */
    public static String extractTextFromTextElement(TextElement element) {
        if (element == null) {
            return "";
        }
        
        if (element.getTextRun() != null) {
            TextRun textRun = element.getTextRun();
            if (textRun.getContent() != null) {
                return textRun.getContent();
            }
        }
        
        // 可以在这里添加对其他类型元素的支持
        // 例如：Mention、Link等
        
        return "";
    }
    
    /**
     * 获取Block中的Text对象
     * 
     * @param block Block对象
     * @return Text对象，如果没有返回null
     */
    public static Text getTextFromBlock(Block block) {
        if (block == null) {
            return null;
        }
        
        // 根据不同的Block类型获取Text对象
        if (block.getText() != null) return block.getText();
        if (block.getHeading1() != null) return block.getHeading1();
        if (block.getHeading2() != null) return block.getHeading2();
        if (block.getHeading3() != null)
        {
            return block.getHeading3();
        }
        if (block.getHeading4() != null) return block.getHeading4();
        if (block.getHeading5() != null) return block.getHeading5();
        if (block.getHeading6() != null) return block.getHeading6();
        if (block.getBullet() != null) return block.getBullet();
        if (block.getOrdered() != null) return block.getOrdered();
        if (block.getCode() != null) return block.getCode();
        if (block.getQuote() != null) return block.getQuote();
        
        return null;
    }
    
    /**
     * 判断Block是否为表格类型
     * 
     * @param block Block对象
     * @return 如果是表格返回true
     */
    public static boolean isTableBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getTable() != null || 
               block.getSheet() != null ||
               block.getBitable() != null ||
               (block.getBlockType() != null && (
                   block.getBlockType() == BLOCK_TYPE_TABLE || 
                   block.getBlockType() == BLOCK_TYPE_SHEET ||
                   block.getBlockType() == BLOCK_TYPE_BITABLE
               ));
    }
    
    /**
     * 判断Block是否为电子表格类型
     * 
     * @param block Block对象
     * @return 如果是电子表格类型返回true
     */
    public static boolean isSheetBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getSheet() != null ||
               (block.getBlockType() != null && 
                block.getBlockType() == BLOCK_TYPE_SHEET);
    }
    
    /**
     * 判断Block是否为文本类型
     * 
     * @param block Block对象
     * @return 如果是文本类型返回true
     */
    public static boolean isTextBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getText() != null || 
               (block.getBlockType() != null && block.getBlockType() == BLOCK_TYPE_TEXT);
    }
    
    /**
     * 判断Block是否为标题类型
     * 
     * @param block Block对象
     * @return 如果是标题类型返回true
     */
    public static boolean isHeadingBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getHeading1() != null || 
               block.getHeading2() != null || 
               block.getHeading3() != null ||
               block.getHeading4() != null || 
               block.getHeading5() != null || 
               block.getHeading6() != null;
    }
    
    /**
     * 判断Block是否为列表类型
     * 
     * @param block Block对象
     * @return 如果是列表类型返回true
     */
    public static boolean isListBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getBullet() != null || block.getOrdered() != null;
    }
    
    /**
     * 判断Block是否为单元格类型
     * 
     * @param block Block对象
     * @return 如果是单元格返回true
     */
    public static boolean isTableCellBlock(Block block) {
        if (block == null) {
            return false;
        }
        
        return block.getTableCell() != null || 
               (block.getBlockType() != null && block.getBlockType() == BLOCK_TYPE_TABLE_CELL);
    }
    
    /**
     * 判断Block是否包含指定文本
     * 
     * @param block Block对象
     * @param text 要查找的文本
     * @return 如果包含返回true
     */
    public static boolean containsText(Block block, String text) {
        if (block == null || text == null || text.isEmpty()) {
            return false;
        }
        
        String blockText = extractTextFromBlock(block);
        return blockText.contains(text);
    }
    
    /**
     * 获取Block的类型名称（用于日志和调试）
     * 
     * @param block Block对象
     * @return 类型名称字符串
     */
    public static String getBlockTypeName(Block block) {
        if (block == null || block.getBlockType() == null) {
            return "Unknown";
        }
        
        switch (block.getBlockType()) {
            case BLOCK_TYPE_PAGE: return "Page";
            case BLOCK_TYPE_TEXT: return "Text";
            case BLOCK_TYPE_HEADING1: return "Heading1";
            case BLOCK_TYPE_HEADING2: return "Heading2";
            case BLOCK_TYPE_HEADING3: return "Heading3";
            case BLOCK_TYPE_HEADING4: return "Heading4";
            case BLOCK_TYPE_HEADING5: return "Heading5";
            case BLOCK_TYPE_HEADING6: return "Heading6";
            case BLOCK_TYPE_BULLET: return "Bullet";
            case BLOCK_TYPE_ORDERED: return "Ordered";
            case BLOCK_TYPE_CODE: return "Code";
            case BLOCK_TYPE_QUOTE: return "Quote";
            case BLOCK_TYPE_TABLE: return "Table";
            case BLOCK_TYPE_TABLE_CELL: return "TableCell";
            default: return "Type_" + block.getBlockType();
        }
    }
    
    /**
     * 创建包含文本的TextElement数组
     * 
     * @param text 文本内容
     * @return TextElement数组
     */
    public static TextElement[] createTextElements(String text) {
        return createTextElements(text, null);
    }
    
    /**
     * 创建包含文本和样式的TextElement数组
     * 
     * @param text 文本内容
     * @param style 文本样式（可选）
     * @return TextElement数组
     */
    public static TextElement[] createTextElements(String text, TextElementStyle style) {
        if (text == null) {
            text = "";
        }
        
        TextElement element = TextElement.newBuilder()
                .textRun(TextRun.newBuilder()
                        .content(text)
                        .textElementStyle(style)
                        .build())
                .build();
        
        return new TextElement[]{element};
    }
    
    /**
     * 合并多个TextElement数组
     * 
     * @param arrays 要合并的TextElement数组
     * @return 合并后的数组
     */
    public static TextElement[] mergeTextElements(TextElement[]... arrays) {
        int totalLength = 0;
        for (TextElement[] array : arrays) {
            if (array != null) {
                totalLength += array.length;
            }
        }
        
        TextElement[] result = new TextElement[totalLength];
        int currentIndex = 0;
        
        for (TextElement[] array : arrays) {
            if (array != null) {
                System.arraycopy(array, 0, result, currentIndex, array.length);
                currentIndex += array.length;
            }
        }
        
        return result;
    }
    
    /**
     * 统计Block中的字数
     * 
     * @param block Block对象
     * @return 字数
     */
    public static int countWords(Block block) {
        String text = extractTextFromBlock(block);
        if (text.isEmpty()) {
            return 0;
        }
        
        // 简单的字数统计逻辑
        // 英文按空格分词，中文按字符计数
        int count = 0;
        String[] words = text.split("\\s+");
        
        for (String word : words) {
            if (!word.isEmpty()) {
                // 检查是否包含中文
                if (word.matches(".*[\\u4e00-\\u9fa5]+.*")) {
                    // 包含中文，统计中文字符数
                    for (char c : word.toCharArray()) {
                        if (c >= 0x4e00 && c <= 0x9fa5) {
                            count++;
                        }
                    }
                } else {
                    // 纯英文单词
                    count++;
                }
            }
        }
        
        return count;
    }
}